<template>
	<w-app-container class="app-home">
		<fx-page-header title="工位"></fx-page-header>
		<fxListFilter @resetSearch='resetSearch'>
					<template slot="row-1" >
						<el-form-item label="工位：">
							<!-- <w-select ref='stationSelect' multiple clearable collapseTags :optionlist='stationList'>
							</w-select> -->
							<w-select-mulity
									ref='stationSelect'
									:optionlist="stationList"
									class="form-input"
								>
							</w-select-mulity>
						</el-form-item>
						<el-form-item label="工位类型：" label-width="110px">
							<!-- <w-select ref='stationTypeSelect' multiple clearable collapseTags :optionlist='stationTypeList'>
							</w-select> -->
							<w-select-mulity
									ref='stationTypeSelect'
									:optionlist="stationTypeList"
									class="form-input"
								>
							</w-select-mulity>
						</el-form-item>
						<el-form-item label="工种：" label-width="110px">
							<!-- <w-select ref='workKindSelect' multiple clearable collapseTags :optionlist='workKindList'>
							</w-select> -->
							<w-select-mulity
									ref='workKindSelect'
									:optionlist="workKindList"
									class="form-input"
								>
							</w-select-mulity>
						</el-form-item>
					</template>
					<template slot="row-2" >
						<el-form-item label="启停状态：" label-width="110px">
							<el-select v-model="enableState" prop="enableState" placeholder="请选择" clearable size='mini' class="form-input">
								<el-option
									v-for="item in stateList"
									:key="item.id"
									:label="item.label"
									:value="item.id"
								>
								</el-option>
							</el-select>
						</el-form-item>
					</template>
					<template slot="tools">
						<el-row>
							<el-button type="primary" size='mini' @click="searchStation">查询</el-button>
							<el-button type="text" size='mini' @click="resetSearch">重置</el-button>
						</el-row>
					</template>
		</fxListFilter>
		<w-app-container direction="row" class="fx-page-first-container">
			<div class="tree-container">
				<fxTree :treeData="treeData" @node-click="nodeClick"></fxTree>
			</div>
			<w-table
					ref="multipleTable"
					:listData="workShopData"
					:tableColumn="workShopColumns"
					:showPagination="true"
					:showColumnFilterBtn="false"
					minWidth="100px"
					:listTotal="totalCount"
					@on-table-row-dbclick="editRow"
					@on-size-change="handleSizeChange"
					@on-current-change="handleCurrentChange">
					<div slot="btn-tools-right" class="tools-right">
						<el-button type="danger" plain size='mini' @click="mutileDel">删除</el-button>
							<el-button type="success" plain size='mini' @click="mutileEnable">启用</el-button>
							<el-button type="info" plain size='mini' @click="mutileDiable">停用</el-button>
							<el-button type="primary"	size='mini' icon="el-icon-plus" @click="addStation">新建工位</el-button>
					</div>
			</w-table>
		</w-app-container>
		<el-dialog :title="dialogTitle" :visible.sync="stationInfoDialogVisible" width='480px'  :before-close="beforeClose">
				<div class="create-area">
				<el-form :model="stationForm" label-position='right' label-width='100px'  :rules="stationRules" ref="stationForm" size='mini' style="height:180px;">
						<el-form-item label="工位编号" prop="code" label-width="110px">
								<el-input v-model="stationForm.code" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="工位名称" prop="name" label-width="110px">
								<el-input v-model="stationForm.name" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="工位类型" prop="stationTypeId" label-width="110px">
								<w-select :multiple='false' v-model="stationForm.stationTypeId" allowCreate
								:clearable='true' :collapseTags='false' :optionlist='stationTypeList' :isBlock='true' @blur="stationTypeBlur" class="form-item-input">
								</w-select>
						</el-form-item>
						<el-form-item label="所属产线" prop="productionLineId" label-width="110px">
								<w-select :multiple='false' v-model="stationForm.productionLineId"
								:clearable='true' :optionlist='workLineList' :isBlock='true' class="form-item-input">
								</w-select>
						</el-form-item>
						<el-form-item label="启停状态" prop="enable" label-width="110px">
								<el-switch v-model="stationForm.enable" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
						</el-form-item>
						<el-form-item label="所属工种" prop="workKindIds" label-width="110px">
								<el-input autocomplete="off" class="form-item-input">
                  <!-- <i class="el-icon-user el-input__icon" slot="suffix" @click="handelWorkKind"></i> -->
									<w-icon slot='suffix' class="el-input__icon" type="relation-workkind" size="mini"  @click="handelWorkKind"></w-icon>
                </el-input>
								<el-tag v-if="stationForm.workKindIds.length >= 1" style="position:absolute;left:0;">
									{{stationForm.workKindIds[0].name}}
								</el-tag>
								<el-tag  style="position:absolute;right:80px;" v-if="stationForm.workKindIds.length > 1">
									+{{stationForm.workKindIds.length - 1}}
								</el-tag>
						</el-form-item>
						<el-form-item label="备注" prop="remark" label-width="110px">
								<el-input
								v-model="stationForm.remark"
								type="textarea"
								:rows="3"
								:maxlength="200"
								placeholder="请输入备注"
								class="form-item-input"
								show-word-limit
								resize="none"
							/>
						</el-form-item>
				</el-form>
				</div>
				<div slot="footer" class="dialog-footer">
						<el-button @click="doClose">取 消</el-button>
						<el-button type="primary" @click="doSave('stationForm')">保 存</el-button>
				</div>
		</el-dialog>
		<transferDialog ref="transferDialog" @on-save-workkind="doSaveWorkKind" :selectStation="selectStation" @on-copy-workkind="copyWorkKind"></transferDialog>
		<fxCopy :hasTree="true" :copyTableData="copyTableData"
			ref="copyDialog"
			:copyTreeData="copyTreeData"
			:columns="copyWorkKindColumns"
			@on-nodeClick="copyNodeClick"
			@on-copysave="copySave">
		</fxCopy>
	</w-app-container>
</template>
<script>
import fxListFilter from '@/components/common/Fx-list-filter.vue'
import fxTree from '@/components/common/Fx-tree.vue'
import fxCopy from '@/components/common/Fx-copy.vue'
import transferDialog from './TransferDialog.vue'
import APP_STATE_CONFIG from '@/config/app_state_config.js'
import FxListStateTag from '@/components/common/Fx-list-state-tag.vue'
export default {
	name: 'station',
	components: {
		fxListFilter,
		fxTree,
		fxCopy,
		transferDialog
	},
	data () {
		return {
			tableHeight: (document.body.clientHeight - 200) + 'px',
			treeData: [],
			selTreeNode: '',
			stateList: APP_STATE_CONFIG.enableState,
			stationList: [],
			stationTypeList: [],
			workKindList: [],
			workLineList: [],
			enableState: '',
			workShopData: [],
			workShopColumns: [
				{ prop: 'code', label: '工位编码', required: true, width: '80px' },
				{ prop: 'name', label: '工位名称', required: true, showOverflowTooltip: true },
				{ prop: 'stationTypeName', label: '工位类型', required: true, showOverflowTooltip: true },
				{ prop: 'productionLineName', label: '所属产线', required: true, showOverflowTooltip: true },
				{
					prop: 'workKindName',
					label: '工种',
					required: true,
					// formatterIcon: true,
					fxRender: this.iconRender,
					iconType: 'relation-workkind'
				},
				{
					prop: 'enable',
					label: '启停状态',
					required: true,
					fxRender: this.enableRender
				},
				{ prop: 'remark', label: '备注', required: true, showOverflowTooltip: true },
				{
					prop: 'modifyUser', label: '修改人', required: true
				},
				{
					prop: 'modifyDate', label: '修改时间', required: true, showOverflowTooltip: true
				},
				{
					prop: 'createUser', label: '创建人', required: true
				},
				{
					prop: 'createDate', label: '创建时间', required: true, showOverflowTooltip: true
				}
			],
			totalCount: 0,
			stationInfoDialogVisible: false,
			dialogTitle: '',
			stationForm: {
				code: '',
				name: '',
				stationTypeId: '',
				productionLineId: '',
				workKindIds: [],
				enable: '1',
				remark: ''
			},
			addstationTypeName: '',
			stationRules: {
				code: [
					{ required: true, message: '请输入工位编号', trigger: 'change' },
					{ min: 1, max: 18, message: '长度最多18个字符', trigger: 'blur' }
				],
				name: [
					{ required: true, message: '请输入工位名称', trigger: 'change' },
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				stationTypeId: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				contactName: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				mobile: [
					{ min: 1, max: 20, message: '长度最多20个字符', trigger: 'blur' }
				],
				productionLineId: [
					{ required: true, message: '请选择所属产线', trigger: 'change' }
				],
				remark: [
					{ min: 1, max: 200, message: '长度最多200个字符', trigger: 'blur' }
				]
			},
			fxDataVerification: null,
			workLineDialogVisible: false,
			selectStation: '',
			editWorkKind: false,
			copyInfoDialogVisible: false,
			copyTreeData: [],
			copyTableData: [],
			copySelTreeId: '',
			copyType: '',
			copyWorkKindColumns: [{
				label: '工位编号',
				prop: 'code',
				width: '80px'
			}, {
				label: '工位名称',
				prop: 'name',
				width: '80px'
			}, {
				label: '所属产线',
				prop: 'productionLineName',
				width: '80px'
			}, {
				label: '工位类型',
				prop: 'stationTypeName',
				width: '80px'
			}]
		}
	},
	created () {
		// 获取左侧树数据
		this.getTreeData()
		// 获取工厂下拉选择项
		this.getStationList()
		this.getStationTypeList()
		this.getWorkKindList()
		this.onRefreshStationList()
	},
	computed: {
		enableFormaterState (val, key) {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('enableState')(val)[key]
			}
		}
	},
	methods: {
		// 树节点点击
		nodeClick (data, node) {
			this.selTreeNode = data.id
			this.onRefreshStationList()
		},
		getTreeData () {
			this.getTreeDataPost().then(res => {
				this.treeData = res
			})
		},
		getTreeDataPost () {
			return new Promise(resolve => {
				this.$fxApi('workshop.orginTree')({
					query: {
						level: '4'
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		getStationList () {
			this.getAllStationList().then(res => {
				this.stationList = res
			})
		},
		getStationTypeList () {
			return new Promise(resolve => {
				this.getAllStationType().then(res => {
					this.stationTypeList = res
					resolve(res)
				})
			})
		},
		// 获取车间下拉选择数据
		getAllStationList () {
			return new Promise(resolve => {
				this.$fxApi('station.findListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取车间类型
		getAllStationType () {
			return new Promise(resolve => {
				this.$fxApi('station.findStationTypeListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取工位所属产线
		getWorkLineList () {
			return new Promise(resolve => {
				this.$fxApi('station.findWorkLineList').then(res => {
					resolve(res)
				})
			})
		},
		// 获取工种
		getWorkKindList () {
			return new Promise(resolve => {
				this.$fxApi('workKind.getWorkKindListAll').then(res => {
					this.workKindList = res
					resolve(res)
				})
			})
		},
		// 列表数据
		onRefreshStationList () {
			this.selstationCount = 0
			const searchParams = {
				pageNum: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageNum) || 1,
				pageSize: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageSize) || 20
			}
			var params = {}
			if (this.enableState !== '') {
				params.enable = this.enableState
			}
			// 工位下拉
			if (this.$refs.stationSelect && this.$refs.stationSelect.currentValue.length >= 1) {
				params.stationIds = this.$refs.stationSelect.currentValue
			}
			// 工位类型下拉
			if (this.$refs.stationTypeSelect && this.$refs.stationTypeSelect.currentValue.length >= 1) {
				params.stationTypeIds = this.$refs.stationTypeSelect.currentValue
			}
			// 工种下拉
			if (this.$refs.workKindSelect && this.$refs.workKindSelect.currentValue.length >= 1) {
				params.workKindIds = this.$refs.workKindSelect.currentValue
			}
			if (this.selTreeNode) {
				params.treeId = this.selTreeNode
			}
			if (Object.keys(params).length !== 0) {
				searchParams.params = params
			}
			return new Promise(resolve => {
				this.$fxApi('station.findAllStation')({
					data: searchParams
				}).then(res => {
					this.totalCount = this.$fxUtils.toNumber(res.total)
					this.workShopData = res.data
					// this.$refs.multipleTable.clearSelected()
					resolve()
				})
			})
		},
		handleSizeChange (val) {
			this.onRefreshStationList()
		},
		handleCurrentChange (val) {
			this.onRefreshStationList()
		},
		addStation () {
			this.editWorkKind = false
			this.selectStation = ''
			return new Promise(resolve => {
				Promise.all([
					this.getAllStationType(),
					this.getWorkLineList(),
					this.getNextCode()
				]).then(([shoplist, factorylist, newCode]) => {
					this.stationTypeList = shoplist
					this.workLineList = factorylist
					this.showDialog(newCode)
					resolve()
				})
			})
		},
		showDialog (code) {
			this.stationInfoDialogVisible = true
			if (this.$refs.stationForm) {
				this.$refs.stationForm.resetFields()
			}
			Object.keys(this.stationForm).map(m => {
				this.stationForm[m] = ''
			})
			this.stationForm.code = code
			this.addstationTypeName = ''
			this.stationForm.workKindIds = []
			this.stationForm.enable = '1'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.stationForm)
			this.dialogTitle = '新建工位'
		},
		renderStationInfo (res) {
			const { code, id, stationTypeId, productionLineId, enable, name, remark } = res
			this.stationForm = {
				code,
				id,
				stationTypeId,
				productionLineId,
				enable,
				name,
				remark
			}
			this.stationForm.workKindIds = res.workKindEntityList ? res.workKindEntityList : []
			this.stationForm.enable = res.enable ? '1' : '0'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.stationForm)
		},
		doClose () {
			this.VerityCompanyData()
		},
		beforeClose () {
			this.VerityCompanyData()
		},
		VerityCompanyData () {
			const isChange = !this.fxDataVerification.checkData(this.stationForm)
			if (isChange) {
				this.$fxCommon.orderListFrontFunc('VeritybeforeClose').then(() => {
					this.doSave('stationForm')
				}).catch(() => {
					this.stationInfoDialogVisible = false
				})
				return false
			} else {
				this.stationInfoDialogVisible = false
			}
		},
		// 工位类型 失去焦点
		stationTypeBlur (e, value) {
			if (value) {
				this.addstationTypeName = value
			}
		},
		doSave (formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.saveOrUpdateStation().then(this.$fxCommon.orderSuccess('save')).then(() => {
						this.stationInfoDialogVisible = false
						this.onRefreshStationList()
					})
				} else {
					return false
				}
			})
		},
		editRow (row, column, event) {
			this.editWorkKind = false
			this.selectStation = row.id
			this.dialogTitle = '修改工位'
			return new Promise(resolve => {
				Promise.all([
					this.getAllStationType(),
					this.getWorkLineList(),
					this.findGroupDetailById(row)
				]).then(([shoplist, factorylist, detail]) => {
					this.stationTypeList = shoplist
					this.workLineList = factorylist
					this.stationInfoDialogVisible = true
					this.renderStationInfo(detail)
					resolve()
				})
			})
			// this.findGroupDetailById(row).then(this.renderWorkShopInfo)
		},
		editRowWorkKind (row) {
			this.editWorkKind = true
			return new Promise(resolve => {
				Promise.all([
					this.getAllStationType(),
					this.getWorkLineList(),
					this.findGroupDetailById(row)
				]).then(([shoplist, factorylist, detail]) => {
					this.stationTypeList = shoplist
					this.workLineList = factorylist
					this.renderStationInfo(detail)
					this.handelWorkKind(row)
					resolve()
				})
			})
		},
		// 批量删除
		mutileDel () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('deleteMulity', _selData)
				.then(this.deleteStation)
				.then(this.$fxCommon.orderSuccess('deleteMulity'))
				.then(this.onRefreshStationList)
		},
		// 批量启用
		mutileEnable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('enableMulity', _selData).then(() => {
				this.handleState(1).then(this.$fxCommon.orderSuccess('enableMulity')).then(this.onRefreshStationList)
			})
		},
		// 批量停用
		mutileDiable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('disableMulity', _selData).then(() => {
				this.handleState(0).then(this.$fxCommon.orderSuccess('disableMulity')).then(this.onRefreshStationList)
			})
		},
		// 启用 停用
		handleState (type) {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = _selData.map(station => station.id)
			return new Promise(resolve => {
				this.$fxApi('station.updateEnables')({
					data: {
						stationIds: ids,
						enable: type
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		resetSearch () {
			this.enableState = ''
			this.$refs.stationSelect.currentValue = []
			this.$refs.stationTypeSelect.currentValue = []
			this.$refs.workKindSelect.currentValue = []
		},
		// 查询集团
		searchStation () {
			this.onRefreshStationList()
		},
		// 获取编号
		getNextCode () {
			return new Promise(resolve => {
				this.$fxApi('station.getNextCode').then(res => {
					resolve(res)
				})
			})
		},
		// 获取集团信息
		findGroupDetailById (row) {
			return new Promise(resolve => {
				this.$fxApi('station.findStationDetailById')({
					query: {
						id: row.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 新建更新集团信息
		saveOrUpdateStation () {
			const { code, id, contactName, enable, mobile, name, remark, productionLineId } = this.stationForm
			const postData = {
				id,
				code,
				contactName,
				enable,
				mobile,
				name,
				remark,
				productionLineId
			}
			// 当是新建车间类型的时候
			if (this.addstationTypeName) {
				postData.archiveTypeDTO = {
					id: '',
					name: this.addstationTypeName
				}
			} else {
				if (this.stationForm.stationTypeId) {
					postData.archiveTypeDTO = {
						id: this.stationForm.stationTypeId,
						name: ''
					}
				}
			}
			// 所属工种
			if (this.stationForm.workKindIds) {
				postData.workKindIds = this.stationForm.workKindIds.map(s => {
					return s.id
				})
			}
			return new Promise(resolve => {
				this.$fxApi('station.saveOrUpdate')({
					data: postData
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 删除集团信息
		deleteStation () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('station.deleteStationMulity')({
					data: {
						stationIds: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		handelWorkKind (row) {
			if (row.id) {
				this.selectStation = row.id ? row.id : ''
			}
			const id = this.stationForm.id || this.selectStation
			this.$refs.transferDialog.open(id, this.stationForm.workKindIds)
		},
		doSaveWorkKind (selKinds) {
			this.stationForm.workKindIds = selKinds
			this.$forceUpdate()
			console.log(this.stationForm.workKindIds.length > 0)
			if (this.editWorkKind) {
				this.saveOrUpdateStation().then(this.$fxCommon.orderSuccess('save')).then(() => {
					this.onRefreshStationList()
				})
			}
		},
		// 复制工种关系
		copyWorkKind () {
			this.getTreeDataPost().then(res => {
				this.copyTreeData = res
				this.copySelTreeId = res[0].id
				this.copyStationList(this.copySelTreeId, this.stationForm.id).then(res => {
					this.copyTableData = res
					this.$refs.copyDialog.open()
				})
			})
		},
		// 复制 右侧工位列表
		copyStationList (copySelTreeId, id) {
			return new Promise(resolve => {
				this.$fxApi('station.copyGetAllStation')({
					query: {
						treeId: copySelTreeId,
						id: id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		copyNodeClick (data, node) {
			this.copySelTreeId = data.id
			this.copyStationList(this.copySelTreeId, this.stationForm.id).then(res => {
				this.copyTableData = res
			})
		},
		copySave (selData, busType) {
			this.copyType = busType
			return this.$fxCommon.orderListFrontFunc('copyMulity', selData)
				.then(this.doCopySave)
				.then(this.$fxCommon.orderSuccess('copyMulity'))
				.then(this.closeDialog)
				.then(this.onRefreshStationList)
		},
		closeDialog () {
			this.$refs.copyDialog.onCancelClick()
		},
		doCopySave (data) {
			const copyIds = data.map(d => {
				return d.id
			})
			return new Promise(resolve => {
				this.$fxApi('station.fromStationTocopyRelation')({
					data: {
						operType: this.copyType,
						copyId: copyIds,
						currentId: this.stationForm.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		enableRender (h, { row }) {
			return <FxListStateTag
				icon={this.enableFormaterState(row.enable, 'icon')}
				label={this.enableFormaterState(row.enable, 'label')}
			></FxListStateTag>
		},
		iconRender (h, { row }) {
			return <w-icon
				slot='icon-slot' type='relation-workkind'
				size="mini"
				rowInfo={row}
				vOn:click={this.editRowWorkKind}
			></w-icon>
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.tree-container {
	display: flex
}
.create-area {
	width: 100%
	height: 350px
	box-sizing: border-box
	.form-item-input {
		width:280px
	}
}
.form-input {
	width: 170px
}
</style>
